package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.dto.EnterpriseUserCheckDto
import cn.exrick.xboot.base.entity.EnterpriseEmployee
import cn.exrick.xboot.base.entity.EnterpriseUserCheck
import cn.exrick.xboot.base.entity.EnterpriseUserStatus
import cn.exrick.xboot.base.mapper.EnterpriseUserCheckMapper
import cn.exrick.xboot.base.service.*
import cn.exrick.xboot.base.vo.EnterpriseUserCheckDetailVo
import cn.exrick.xboot.base.vo.EnterpriseUserCheckListVo
import cn.exrick.xboot.base.vo.EnterpriseUserDetailVo
import cn.exrick.xboot.core.common.constant.CommonConstant
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import cn.exrick.xboot.core.entity.User
import cn.exrick.xboot.core.entity.UserRole
import cn.exrick.xboot.core.service.RoleService
import cn.exrick.xboot.core.service.UserService
import cn.exrick.xboot.core.service.mybatis.IUserRoleService
import cn.exrick.xboot.message.ISendMessageService
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*

/**
 * 企业审核接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class IEnterpriseUserCheckServiceImpl : ServiceImpl<EnterpriseUserCheckMapper?, EnterpriseUserCheck?>(), IEnterpriseUserCheckService {

    @Autowired
    private lateinit var securityUtil: SecurityUtil

    @Autowired
    private lateinit var iEnterpriseUserService: IEnterpriseUserService

    @Autowired
    private lateinit var iEnterpriseUserStatusService: IEnterpriseUserStatusService

    @Autowired
    private lateinit var iAreaService: IAreaService

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var iEnterpriseEmployeeService: IEnterpriseEmployeeService

    @Autowired
    private lateinit var iUserRoleService: IUserRoleService

    @Autowired
    private lateinit var roleService: RoleService

    @Autowired
    private lateinit var iSendMessageService: ISendMessageService


    override fun getCheckEnterpriseList(pageVo: PageVo, status: Int): Result<MutableMap<String, Any?>>? {

        val enterpriseCheckWrapper = KtQueryWrapper(EnterpriseUserCheck::class.java)
                .eq(EnterpriseUserCheck::checkUser, securityUtil.currUser.id)
                .orderByDesc(EnterpriseUserCheck::createTime)

        when (status) {
            1 -> {

                enterpriseCheckWrapper.eq(EnterpriseUserCheck::checkStatus, CommonConstant.PRE_CHECK)
            }
            else -> {

                enterpriseCheckWrapper.ne(EnterpriseUserCheck::checkStatus, CommonConstant.PRE_CHECK)
                        .eq(EnterpriseUserCheck::checkUser, securityUtil.currUser.id)
            }
        }

       return ToolUtil.setListToNul(list(enterpriseCheckWrapper))?.run {

            val result:MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { getEnterpriseCheckListVo(it!!.id) }.toMutableList())

            ResultUtil.data(result, "获取公司审核数据成功!")
        } ?: ResultUtil.error(201, "暂无数据")

    }

    private fun getEnterpriseCheckListVo(id: String): EnterpriseUserCheckListVo? {

        return getById(id)?.run {

            EnterpriseUserCheckListVo().apply {

                //1.企业信息
                iEnterpriseUserService.getById(enterpriseUserId)?.let {

                    companyName = it.companyName
                    companyAvatar = it.avatar
                    applyTime = it.createTime
                }

                //2.审核信息
                ToolUtil.copyProperties(this@run, this)
            }
        }
    }

    override fun getCheckEnterpriseDetail(id: String): Result<EnterpriseUserCheckDetailVo>? {

        return getById(id)?.run {

           ResultUtil.data( EnterpriseUserCheckDetailVo().apply {

               enterpriseUserCheckListVo = getEnterpriseCheckListVo(this@run.id)

               //1.企业信息
               iEnterpriseUserService.getById(enterpriseUserId)?.let {

                   ToolUtil.copyProperties(it, this)
                   enterpriseAddress = iAreaService.getAreaFullNameByAreaId(areaId)?.plus(it.registerAddress)
                   licensePic = it.licensePic?.split(",")?.toMutableList()
                   identityCard = it.identityCard?.split(",")?.toMutableList()
               }

               //2.审核信息
               ToolUtil.copyProperties(this@run, this)
               companyId = this@run.id
               checkUserName = userService.get(checkUser)?.nickname
               managementForms = iEnterpriseUserStatusService.getOne(KtQueryWrapper(EnterpriseUserStatus::class.java)
                       .eq(EnterpriseUserStatus::enterpriseUserId, enterpriseUserId))?.managementForms
           }, "获取详情信息成功")
        } ?: ResultUtil.error(201, "不存在当前审核数据!")

    }

    override fun checkEnterpriseUser(enterpriseUserCheckDto: EnterpriseUserCheckDto): Result<Any?>? {


       return try {

            getById(enterpriseUserCheckDto.id)?.run {

                iEnterpriseUserService.getById(enterpriseUserId)?.let {

                    //1.1 审核表信息
                    ToolUtil.copyProperties(enterpriseUserCheckDto, this)
                    checkUser = securityUtil.currUser.id
                    checkTime = Date()
                    updateById(this@run)

                    if (enterpriseUserCheckDto.checkStatus == CommonConstant.CHECK_PASS) {

                        //1.2 企业信息变为存续
                        iEnterpriseUserStatusService.getOne(KtQueryWrapper(EnterpriseUserStatus::class.java).eq(EnterpriseUserStatus::enterpriseUserId, enterpriseUserId))?.let {

                            it.managementForms = CommonConstant.SUBSIST
                            iEnterpriseUserStatusService.updateById(it)
                        }

                        //1.3 生成高管用户
                        iEnterpriseUserService.getById(enterpriseUserId)?.let {

                          val userInsert = userService.update(userService.get(it.createBy).apply {

                                username = it.registerUserPhone
                                nickname = it.registerUserName
                                password = it.password
                                areaId = it.areaId
                                street = it.registerAddress
                                address = iAreaService.getAreaFullNameByAreaId(it.areaId)?.plus(it.registerAddress)
                                avatar = it.avatar
                                mobile = it.registerUserPhone
                            })

                            //删除之前的角色
                            iUserRoleService.remove(KtQueryWrapper(UserRole::class.java).eq(UserRole::userId, userInsert.id))

                                //1.3.1 角色
                                iUserRoleService.save(UserRole().apply {

                                    userId = userInsert.id
                                    roleId = roleService.getRoleIdByRoleName(CommonConstant.ROLE_TOP_MANAGER)
                                })

                                //1.3.2 员工
                                iEnterpriseEmployeeService.save(EnterpriseEmployee().apply {

                                    userId = userInsert.id
                                    enterpriseId = enterpriseUserId
                                })
                        }

                        //1.4 发送短信提醒
                        iSendMessageService.sendSmsCode(it.legalPhone!!, "code", "", "SMS_200712327")
                    }

                    //1.5 发送审核失败短信提醒
                    enterpriseUserCheckDto.checkReason?.let { reason ->

                        iSendMessageService.sendSmsCode(it.legalPhone!!, "code", reason, "SMS_200712329")
                    }
                }
            }

            ResultUtil.success("操作成功")
        } catch (e : Exception) {

            ResultUtil.error(e.message)
        }
    }

}